<template>
  <div class="downloads">
    <!-- 轮播图区域 -->
    <div class="carousel-banner" v-if="carouselData.length > 0">
      <el-carousel
        height="400px"
        :autoplay="true"
        :interval="5000"
        arrow="never"
        indicator-position="none"
      >
        <el-carousel-item v-for="(item, index) in carouselData" :key="index">
          <div
            class="carousel-item"
            :style="{ backgroundImage: `url(${item.image})` }"
          >
            <div class="carousel-overlay">
              <div class="container">
                <div class="carousel-content">
                  <h1 class="carousel-title">{{ item.title }}</h1>
                  <p class="carousel-subtitle" v-if="item.subtitle">
                    {{ item.subtitle }}
                  </p>
                  <p class="carousel-description" v-if="item.description">
                    {{ item.description }}
                  </p>
                  <el-button
                    v-if="item.buttonText"
                    type="primary"
                    size="large"
                    @click="handleCarouselAction(item.action)"
                  >
                    {{ item.buttonText }}
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </el-carousel-item>
      </el-carousel>
    </div>

    <!-- 页面标题（当没有轮播图时显示） -->
    <div class="page-header" v-else>
      <div class="container">
        <h1>下载中心</h1>
        <p>获取展会相关资料和文档</p>
      </div>
    </div>

    <section class="section">
      <div class="container">
        <div class="downloads-grid">
          <div
            class="download-card card"
            v-for="item in downloadItems"
            :key="item.id"
          >
            <div class="download-icon">
              <el-icon><component :is="getIconComponent(item.icon)" /></el-icon>
            </div>
            <div class="download-content">
              <h3>{{ item.title }}</h3>
              <p>{{ item.description }}</p>
              <div class="download-meta">
                <span class="file-size">{{ item.size }}</span>
                <span class="file-type">{{ item.type }}</span>
                <span class="update-time">更新: {{ item.updateTime }}</span>
              </div>
              <div class="download-actions">
                <el-button type="primary" @click="handleDownload(item)">
                  <el-icon><Download /></el-icon>
                  下载文件
                </el-button>
                <el-button v-if="item.preview" @click="handlePreview(item)">
                  <el-icon><View /></el-icon>
                  预览
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  </div>
</template>

<script>
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { Download, View, Document } from "@element-plus/icons-vue";
import { downloadApi, subpageApi } from "@/api/user";

export default {
  name: "Downloads",
  components: {
    Download,
    View,
    Document,
  },
  setup() {
    const downloadItems = ref([]);
    const otherDownloads = ref([]);
    const carouselData = ref([]);

    const loadCarouselData = async () => {
      try {
        const response = await subpageApi.getContentByType(
          "carousel_downloads"
        );
        if (response && response.code === "200" && response.data) {
          carouselData.value = response.data
            .filter((item) => item.status === "active")
            .map((item) => {
              const content =
                typeof item.content === "string"
                  ? JSON.parse(item.content)
                  : item.content;
              return {
                id: item.id,
                title: item.title,
                subtitle: item.subtitle || "",
                description: content.description || "",
                image: item.imageUrl || content.image || "",
                buttonText: content.buttonText || "",
                action: content.action || "",
              };
            })
            .sort((a, b) => a.sort - b.sort);
          console.log("轮播图数据加载成功:", carouselData.value);
        }
      } catch (error) {
        console.error("加载轮播图数据失败:", error);
      }
    };

    const handleCarouselAction = (action) => {
      if (action && action.type === "link" && action.url) {
        window.open(action.url, "_blank");
      }
    };

    const loadDownloads = async () => {
      try {
        const res = await downloadApi.getDownloadList({ limit: 100 });
        if (
          res &&
          (res.code === "200" || res.code === 200) &&
          Array.isArray(res.data)
        ) {
          const files = res.data.map((f) => ({
            id: f.id,
            title: f.title || f.fileName,
            description: f.description || "",
            icon: "Document",
            size: f.fileSize
              ? `${(f.fileSize / 1024 / 1024).toFixed(1)} MB`
              : "",
            type: (f.fileType || "").toUpperCase(),
            updateTime: f.updatedTime || f.createdTime || "",
            preview: f.preview === 1 || f.preview === true,
            url: f.filePath,
          }));
          // 拆分为两组：主卡片和其他资料
          downloadItems.value = files.slice(0, 6);
          otherDownloads.value = files.slice(6);
        }
      } catch (e) {
        console.error("加载下载列表失败", e);
      }
    };

    const getFileNameFromUrl = (url) => {
      try {
        const pathname = new URL(url, window.location.origin).pathname;
        const last = pathname.substring(pathname.lastIndexOf("/") + 1);
        return decodeURIComponent(last || "download");
      } catch (e) {
        return "download";
      }
    };

    const triggerDownload = (url, filename) => {
      const a = document.createElement("a");
      a.href = url;
      a.download = filename || "download";
      a.target = "_blank";
      a.rel = "noopener";
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    };

    const ensureAbsoluteUrl = (url) => {
      if (!url) return "";
      if (/^https?:\/\//i.test(url)) return url;
      try {
        const base = window.location.origin;
        return new URL(url, base).toString();
      } catch {
        return url;
      }
    };

    const handleDownload = async (item) => {
      // 优先通过后端下载接口触发下载计数 + 获取真实下载地址
      try {
        if (item.id) {
          const res = await downloadApi.downloadFile(item.id);
          // 若返回JSON包装
          if (res && (res.code === "200" || res.code === 200)) {
            const urlFromApi = res.data?.url || res.data?.filePath || res.data;
            if (urlFromApi) {
              const ext = (item.type || "").toLowerCase();
              const baseName =
                item.title || item.fileName || getFileNameFromUrl(urlFromApi);
              const fileName = baseName.includes(".")
                ? baseName
                : ext
                ? `${baseName}.${ext.toLowerCase()}`
                : baseName;
              const absUrl = ensureAbsoluteUrl(urlFromApi);
              try {
                const resp = await fetch(absUrl, { credentials: "include" });
                if (!resp.ok) throw new Error("下载失败");
                const blob = await resp.blob();
                const blobUrl = URL.createObjectURL(blob);
                triggerDownload(blobUrl, fileName);
                setTimeout(() => URL.revokeObjectURL(blobUrl), 10000);
              } catch (_) {
                window.open(absUrl, "_blank");
              }
              return;
            }
          }
          // 若后端直接返回文件/重定向，走新窗口触发服务器计数
          window.open(`/api/download/file/${item.id}`, "_blank");
          return;
        }
      } catch (e) {
        // 忽略，回退到直链
      }
      // 回退：使用直链地址（不一定能计数）
      if (!item.url) {
        ElMessage.error("文件地址不存在");
        return;
      }
      const ext = (item.type || "").toLowerCase();
      const baseName =
        item.title || item.fileName || getFileNameFromUrl(item.url);
      const fileName = baseName.includes(".")
        ? baseName
        : ext
        ? `${baseName}.${ext.toLowerCase()}`
        : baseName;
      try {
        const absUrl = ensureAbsoluteUrl(item.url);
        const resp = await fetch(absUrl, { credentials: "include" });
        if (!resp.ok) throw new Error("下载失败");
        const blob = await resp.blob();
        const blobUrl = URL.createObjectURL(blob);
        triggerDownload(blobUrl, fileName);
        setTimeout(() => URL.revokeObjectURL(blobUrl), 10000);
      } catch (e) {
        window.open(item.url, "_blank");
      }
    };

    const handlePreview = (item) => {
      // 模拟预览
      ElMessage.info(`预览文件: ${item.title}`);
      console.log("预览文件:", item);
    };

    const downloadMap = () => {
      const mapUrl =
        "https://via.placeholder.com/2400x1800/667eea/ffffff?text=FAIR+plus+%E9%AB%98%E6%B8%85%E5%9C%B0%E5%9B%BE";
      triggerDownload(mapUrl, "展会高清地图.jpg");
    };

    const getIconComponent = (iconName) => {
      const iconMap = {
        Document: Document,
      };
      return iconMap[iconName] || Document;
    };

    onMounted(() => {
      loadDownloads();
      loadCarouselData();
    });

    return {
      downloadItems,
      otherDownloads,
      carouselData,
      handleDownload,
      handlePreview,
      handleCarouselAction,
      downloadMap,
      getIconComponent,
    };
  },
};
</script>

<style scoped>
.downloads {
  min-height: 100vh;
  background: #f8f9fa;
  /* padding-top: 70px; */
}

/* 轮播图样式 */
.carousel-banner {
  margin-top: 0;
}

.carousel-item {
  height: 400px;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  position: relative;
}

.carousel-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  /* padding-top: 130px; */
}

.carousel-content {
  text-align: left;
  color: white;
  max-width: 100%;
}

.carousel-title {
  font-size: 48px;
  font-weight: bold;
  margin-bottom: 20px;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
}

.carousel-subtitle {
  font-size: 24px;
  margin-bottom: 15px;
  opacity: 0.9;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
}

.carousel-description {
  font-size: 16px;
  margin-bottom: 20px;
  opacity: 0.8;
  line-height: 1.6;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
}

.section {
  padding: 60px 0;
}

.page-header {
  background: linear-gradient(135deg, #320063 0%, #4a0a8a 100%);
  color: white;
  padding: 80px 0;
  text-align: center;
}

.page-header h1 {
  font-size: 48px;
  margin-bottom: 20px;
}

.page-header p {
  font-size: 18px;
  opacity: 0.9;
}

.downloads-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 30px;
}

.download-card {
  display: flex;
  padding: 30px;
  gap: 20px;
  transition: transform 0.3s ease;
}

.download-card:hover {
  transform: translateY(-5px);
}

.download-icon {
  width: 60px;
  height: 60px;
  background: linear-gradient(
    135deg,
    var(--e-global-color-a3699a4) 0%,
    var(--e-global-color-5c1ca3d) 100%
  );
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
  flex-shrink: 0;
}

.download-content {
  flex: 1;
}

.download-content h3 {
  font-size: 20px;
  margin-bottom: 10px;
  color: #2c3e50;
}

.download-content p {
  color: #666;
  line-height: 1.6;
  margin-bottom: 15px;
}

.download-meta {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.download-meta span {
  font-size: 12px;
  color: #666;
  background: #f0f0f0;
  padding: 4px 8px;
  border-radius: 4px;
}

.download-actions {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.map-section {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 40px;
  align-items: start;
}

.map-container {
  position: relative;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
}

.map-image {
  width: 100%;
  height: auto;
  display: block;
}

.map-overlay {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
}

.map-info h3 {
  font-size: 24px;
  margin-bottom: 20px;
  color: #2c3e50;
}

.venue-info {
  list-style: none;
  padding: 0;
}

.venue-info li {
  padding: 10px 0;
  border-bottom: 1px solid #eee;
  color: #666;
}

.venue-info li:last-child {
  border-bottom: none;
}

.venue-info strong {
  color: #2c3e50;
}

.other-downloads {
  max-width: 800px;
  margin: 0 auto;
}

.download-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.download-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.download-item:hover {
  transform: translateY(-2px);
}

.item-info h4 {
  font-size: 16px;
  margin-bottom: 5px;
  color: #2c3e50;
}

.item-info p {
  color: #666;
  margin-bottom: 10px;
  font-size: 14px;
}

.item-meta {
  display: flex;
  gap: 15px;
  font-size: 12px;
  color: #999;
}

.bg-light {
  background: #f8f9fa;
}

@media (max-width: 768px) {
  .page-header h1 {
    font-size: 32px;
  }

  .downloads-grid {
    grid-template-columns: 1fr;
  }

  .download-card {
    flex-direction: column;
    text-align: center;
  }

  .map-section {
    grid-template-columns: 1fr;
    gap: 30px;
  }

  .download-item {
    flex-direction: column;
    text-align: center;
    gap: 15px;
  }

  .item-meta {
    justify-content: center;
  }
}
</style>
